import Base from '../../base'
import view from '../../views/game/map.json'

export default class Map extends Base {

	constructor(scene) {
		super(scene,view)
		this.map = {
			mapId: 3,//地图编号
			picW: 400,
			picH: 300,
			maxW: 9200,
			maxH: 6300,
			stepX: 32,//步伐像素
			stepY: 32,
		}
		this.mapMove = {x: 0, y: 0}
		this.lastXY = {x: 0, y: 0}
	}

	create() {
		this.view['node'].setInteractive()
		this.view['node'].on(Phaser.Input.Events.POINTER_DOWN, this.roleMove, this)
	}

	update (time, delta)
	{
		if(this.mapMove.x != 0 || this.mapMove.y != 0){
			let x = this.mapMove.x == 0 ? 0 : (this.mapMove.x > 0 ? 1 : -1)
			let y = this.mapMove.y == 0 ? 0 : (this.mapMove.y > 0 ? 1 : -1)
			this.view['node'].getAll().forEach(v =>{
				v.x -= x
				v.y -= y
			})
			this.mapMove.x -= x
			this.mapMove.y -= y
		}
	}

    loadMap(){
		let picX = Math.ceil(this.scene.playerModule.player.x * this.map.stepX / this.map.picW)
        let picY = Math.ceil(this.scene.playerModule.player.y * this.map.stepY / this.map.picH)
        for (let indexX = -2; indexX < 4; indexX++) {
            for (let indexY = -2; indexY < 4; indexY++) {
				let picKey = 'map/'+this.map.mapId+'/' + (picY + indexY) + '_' + (picX + indexX)
				this.addImage(picKey + '.jpg', indexX * this.map.picW, indexY * this.map.picH, this.view['node'])
            }
        }
	}

    roleMove(e){
		if(this.mapMove.x != 0 || this.mapMove.y != 0){
			return
		}

		let moveDir = {x:0, y:0};

		if(e.rightButtonDown()){
			let xy = e.positionToCamera(e.camera)
			this.lastXY.x = xy.x
			this.lastXY.y = xy.y
			moveDir = this.scene.playerModule.move(this.lastXY, 2)
			moveDir.x = moveDir.x * this.map.stepX * 2
			moveDir.y = moveDir.y * this.map.stepY * 2
		}else{
			this.lastXY = {x: Math.floor(e.downX), y: Math.floor(e.downY)}
			moveDir = this.scene.playerModule.move(this.lastXY)
			moveDir.x = moveDir.x * this.map.stepX
			moveDir.y = moveDir.y * this.map.stepY
		}

		this.mapMove = moveDir
	}
}